package study.itheima.stusys;

import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/AddStu")
public class AddStu extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        Stu stu = new Stu();
        Map<String, String[]> map = req.getParameterMap();
        try {
            BeanUtils.populate(stu,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String realPath = getServletContext().getRealPath("/WEB-INF/classes/stu.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(realPath,true));
        bw.write(stu.toString());
        bw.newLine();
        bw.close();
        resp.setContentType("Text/Html;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.write("添加成功,两秒后自动跳转...");
        //设置响应消息头定时刷新
        resp.setHeader("Refresh","2;URL=/request");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
